import re
import base64
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView

from bigevents_admin.serializers.userinfo import UserInfoSerializer
from fdfs_client.client import Fdfs_client
from bigevents_admin.authenticate import JWTAuth


class UserInforView(APIView):
    """用户信息视图"""
    authentication_classes = (JWTAuth,)

    def get(self, request):
        """获取用户个人信息"""
        user = request.user
        if user:
            # 指定序列化器
            serializer = UserInfoSerializer(user)
            data = serializer.data
            if data['user_pic'] is not None:
                user_pic = settings.FDFS_BASE_URL + user.user_pic.url
                data['user_pic'] = user_pic
            # 构造返回数据
            return Response({'status': 0, 'message': '获取用户基本信息成功！', 'data': data})
        else:
            return Response({'status': 1, 'message': '获取用户基本信息失败！'})

    def post(self, request):
        """更新用户基本信息"""
        # 获取前端数据
        data = request.data
        # 验证数据
        serializer = UserInfoSerializer(data=data)
        serializer.is_valid()
        try:
            # 获取用户User对象
            user = request.user
            user.username = request.data.get('username')
            user.nickname = request.data.get('nickname')
            user.email = request.data.get('email')
            user.save()
        except Exception as e:
            return Response({'status': 1, 'message': '修改用户信息失败！'})
        return Response({'status': 0, 'message': '修改用户信息成功！'})


class UpdatepwdView(APIView):
    """重置密码"""
    authentication_classes = (JWTAuth,)

    def post(self, request):
        # 获取用户对象
        user = request.user
        # 判断用户是否通过认证
        if not user:
            return Response({'status': 1, 'message': '更新密码失败！'})
        # 认证通过，获取前端请求体参数
        oldPwd = request.data.get('oldPwd')
        newPwd = request.data.get('newPwd')
        # 验证参数
        ret_old = re.match('^[\\S]{6,12}$', oldPwd)
        ret_new = re.match('^[\\S]{6,12}$', newPwd)
        # 判断密码是否符合要求
        if (ret_old and ret_new) is None and (ret_old == ret_new):
            return Response({'status': 1, 'message': '更新密码失败！'})
        # 验证旧密码
        if user.check_password(oldPwd):
            user.set_password(newPwd)
            user.save()
            return Response({'status': 0, 'message': '更新密码成功！'})
        else:
            return Response({'status': 1, 'message': '更新密码失败！'})


class UpdateAatarView(APIView):
    """更新头像"""
    authentication_classes = (JWTAuth,)
    
    def post(self, request):
        user = request.user
        # 获取前端传来的base64字符串
        avatar = request.data.get('avatar')
        avatar_str = avatar.replace('data:image/png;base64,', '')
        # 将base64字符串转换为bytes
        avatar_bytes = base64.b64decode(avatar_str)
        # 创建fdfs实例
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片至fdfs
        ret = client.upload_by_buffer(avatar_bytes)
        # 判断上传是否成功，是则保存图片地址到数据库
        if ret['Status'] == 'Upload successed.':
            user.user_pic = ret['Remote file_id']
            user.save()
            return Response({'status': 0, 'message': '更新头像成功！'})
        else:
            return Response({'status': 1, 'message': '更新头像失败！'})

